<?php
use Workerman\Worker;
require_once __DIR__ . '/../vendor/autoload.php';

$tcpWorker = new Worker('tcp://0.0.0.0:2346');
$tcpWorker->clientMap = []; // 存储客户端注册信息

$tcpWorker->onMessage = function ($connection, $data) use ($tcpWorker) {
    $command = json_decode($data, true);
    // 客户端注册
    if ($command['type'] === 'register') {
        $tcpWorker->clientMap[$command['id']] = [
            'public_ip'   => $command['public_ip'],
            'public_port' => $command['public_port']
        ];
        $connection->send(json_encode(['status' => 'registered']));
    }
    // 查询对端地址
    elseif ($command['type'] === 'get_peer') {
        $peerInfo = $tcpWorker->clientMap[$command['peer_id']] ?? null;
        $connection->send(json_encode($peerInfo));
    }
    // 新增指令转发
    elseif ($command['type'] === 'request_peer') {
        $peerInfo = $tcpWorker->clientMap[$command['target_id']] ?? null;
        if ($peerInfo) {
            $connection->send(json_encode([
                'type' => 'peer_info',
                'ip'   => $peerInfo['public_ip'],
                'port' => $peerInfo['public_port']
            ]));
        }
    }
};

Worker::runAll();